package com.lxk.concurrency.example.aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CountDownLatch：闭锁，可以完成线程之间相互等待，直到所有线程准备完毕，全部释放
 * @author leong
 *
 */
public class CountDownLatchExample1 {

	private final static int threadCount = 200;

	public static void main(String[] args) throws Exception {

		ExecutorService exec = Executors.newCachedThreadPool();

		final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

		for (int i = 0; i < threadCount; i++) {
			final int threadNum = i;

			exec.execute(() -> {
				try {
					test(threadNum);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {

					// N - 1
					countDownLatch.countDown();
				}

			});
		}

		// 方法会一直阻塞直到计数器为0，主线程才会继续往下执行
		countDownLatch.await();
		System.out.println("finish");

		// 关闭线程池
		exec.shutdown();
	}

	private static void test(int threadNum) throws Exception {
		Thread.sleep(100);
		System.out.println(threadNum);
		Thread.sleep(100);
	}
}
